package com.ellricky.baselib.http.callback;

import android.app.Activity;

import com.andr.common.http.NetConst;
import com.andr.common.http.callback.BaseCallback;
import com.andr.common.http.callback.GsonRespParser;
import com.andr.common.http.entity.CommonEntity;
import com.andr.common.util.EmptyUtil;
import com.andr.common.util.ToastUtil;
import com.ellricky.baselib.http.entity.EDataEntiy;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


public abstract class ECallback<T> extends BaseCallback {

    private Class mClazz;

    public ECallback(Activity context) {
        this(context, true);
    }

    public ECallback(Activity context, boolean showLoading) {
        this(context, showLoading, "");

    }

    public ECallback(Activity context, boolean showLoading, String loadMsg) {
        super(context, showLoading, loadMsg);
        Type genType = getClass().getGenericSuperclass();
        if (genType != null) {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            mClazz = (Class) params[0];
        }
    }

    @Override
    public int dataFlag() {
        return NetConst.FLAG_JO;
    }

    @Override
    public void parseDataJO(String code, String msg, JSONObject dataJO) {
        EDataEntiy<T> entity = parseEntity(dataJO);
        if (entity != null) {
            if (NetConst.RET_CODE_SUCCESS.equals(code)) {
                T data = entity.getData();
                if (data != null) onSuccess(entity.getData(), msg);
            } else {
                onErrorCode(code, msg);
            }

        } else {
            onErrorCode(NetConst.CODE_PARSE_NULL, "解析错误");
        }
    }


    public abstract void onSuccess(T data, String msg);

    public void onErrorCode(String code, String msg) {
        // 如需处理异常code,需重写该方法
        if (!EmptyUtil.isEmpty(msg))
            ToastUtil.show(mContext, msg);
    }


    private EDataEntiy<T> parseEntity(JSONObject response) {
        Type gsonType = new GsonRespParser(EDataEntiy.class, new Class[]{mClazz});
        return new Gson().fromJson(response.toString(), gsonType);
    }

}
